from django.db import models
from django.core.exceptions import ValidationError
from django.db.models import Count, Q


class Deck(models.Model):
    """用户卡组"""
    user = models.ForeignKey('accounts.User', on_delete=models.CASCADE, null=True, blank=True, verbose_name="用户")
    name = models.CharField(max_length=100, verbose_name="卡组名称")
    is_active = models.BooleanField(default=True, verbose_name="是否可用")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "卡组"
        verbose_name_plural = "卡组"
        ordering = ['-updated_at']
        constraints = [
            models.UniqueConstraint(
                fields=['user', 'name'],
                name='unique_user_deck_name',
                condition=models.Q(user__isnull=False)
            )
        ]
    
    def __str__(self):
        if self.user:
            return f"{self.user.nickname} - {self.name}"
        else:
            return f"AI - {self.name}"
    
    def clean(self):
        """验证卡组"""
        # 检查用户卡组数量限制（只对真实用户检查）
        if self.user and not self.pk:  # 新建卡组时检查
            user_deck_count = Deck.objects.filter(user=self.user, is_active=True).count()
            if user_deck_count >= 10:
                raise ValidationError("每个用户最多只能拥有10个卡组")
        elif not self.user:
            # AI卡组不需要检查用户限制
            pass
        else:
            # 只有已存在的卡组才检查卡牌数量
            if self.deck_cards.count() > 5:
                raise ValidationError("卡组最多只能包含5张卡牌")
            
            # 检查卡组规则
            self.validate_deck_rules()
    
    def save(self, *args, **kwargs):
        """保存时自动验证"""
        self.clean()
        super().save(*args, **kwargs)
    
    def validate_deck_rules(self):
        """验证卡组构建规则"""
        deck_cards = self.deck_cards.all()
        
        # 规则1: 最多5张卡牌
        total_cards = sum(dc.quantity for dc in deck_cards)
        if total_cards > 5:
            raise ValidationError("卡组最多只能包含5张卡牌")
        
        # 规则2: 最多1张5星卡牌
        five_star_cards = sum(dc.quantity for dc in deck_cards if dc.card.star_level == 5)
        if five_star_cards > 1:
            raise ValidationError("卡组最多只能包含1张5星卡牌")
        
        # 规则3: 相同卡牌只能携带1张
        for deck_card in deck_cards:
            if deck_card.quantity > 1:
                raise ValidationError(f"相同卡牌只能携带1张，{deck_card.card.name} 携带了 {deck_card.quantity} 张")
    
    @property
    def total_cards(self):
        """卡组总卡牌数"""
        return self.deck_cards.aggregate(total=models.Sum('quantity'))['total'] or 0
    
    @property
    def is_valid(self):
        """检查卡组是否有效"""
        try:
            self.validate_deck_rules()
            return True
        except ValidationError:
            return False
    
    @property
    def validation_errors(self):
        """获取卡组验证错误信息"""
        try:
            self.validate_deck_rules()
            return []
        except ValidationError as e:
            return [str(e)]


class DeckCard(models.Model):
    """卡组中的卡牌"""
    deck = models.ForeignKey(Deck, on_delete=models.CASCADE, related_name='deck_cards', verbose_name="卡组")
    card = models.ForeignKey('cards.Card', on_delete=models.CASCADE, verbose_name="卡牌")
    quantity = models.IntegerField(default=1, verbose_name="数量")
    
    class Meta:
        verbose_name = "卡组卡牌"
        verbose_name_plural = "卡组卡牌"
        unique_together = ['deck', 'card']
    
    def __str__(self):
        return f"{self.deck.name} - {self.card.name} x{self.quantity}"
    
    def clean(self):
        """验证卡组卡牌"""
        if self.quantity <= 0:
            raise ValidationError("卡牌数量必须大于0")
        
        # 根据卡组规则，相同卡牌只能携带1张
        if self.quantity > 1:
            raise ValidationError("相同卡牌只能携带1张")
        
        # 检查用户是否拥有足够的卡牌（只对真实用户检查）
        if self.deck.user:
            from apps.cards.models import UserCard
            try:
                user_card = UserCard.objects.get(user=self.deck.user, card=self.card)
                if user_card.quantity < self.quantity:
                    raise ValidationError(f"您只拥有 {user_card.quantity} 张 {self.card.name}")
            except UserCard.DoesNotExist:
                raise ValidationError(f"您没有 {self.card.name} 这张卡牌")
